package com.xinxing.learning.security.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.session.FindByIndexNameSessionRepository;
import org.springframework.session.data.redis.config.annotation.web.http.EnableRedisHttpSession;
import org.springframework.session.security.SpringSessionBackedSessionRegistry;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

@Slf4j
@EnableRedisHttpSession
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private final FindByIndexNameSessionRepository findByIndexNameSessionRepository;

    public SecurityConfig(FindByIndexNameSessionRepository findByIndexNameSessionRepository) {
        this.findByIndexNameSessionRepository = findByIndexNameSessionRepository;
    }

    @Bean
    public UserDetailsService userDetailsService() {
        InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
        inMemoryUserDetailsManager.createUser(User.withUsername("root").password("{noop}123").roles("admin", "supper").build());
        return inMemoryUserDetailsManager;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .logout()
                .invalidateHttpSession(true) // 默认为true
                .clearAuthentication(true) // 默认为true
                .and()
                .csrf().disable()
                .sessionManagement()
                // 最多同时允许几个客户端同时登录 后登录的会挤掉老的登录
                .maximumSessions(1)
                // 传统web开发 如果登录过期 重新跳转到登录界面
                // .expiredUrl("/login")
                // 前后端分离开发 如果登录过期 返回json数据
                .expiredSessionStrategy(event -> {
                    HttpServletResponse response = event.getResponse();
                    HashMap<String, Object> result = new HashMap<>();
                    result.put("msg", "请重新登录");
                    result.put("status", HttpStatus.UNAUTHORIZED.value());
                    response.setContentType("application/json;charset=UTF-8");
                    String resultStr = new ObjectMapper().writeValueAsString(result);
                    log.info("onAuthenticationSuccess() returned: " + resultStr);
                    response.getWriter().println(resultStr);
                    response.flushBuffer();
                })
                .sessionRegistry(sessionRegistry())
                // 当前账户如果已经登录成功 禁止在其他设备上再次登录
                .maxSessionsPreventsLogin(true)
        ;
    }

    @Bean
    public SpringSessionBackedSessionRegistry sessionRegistry() {
        return new SpringSessionBackedSessionRegistry(findByIndexNameSessionRepository);
    }

    /**
     * spring security配置禁止再次登录数参数后，登出系统后无法再次登陆
     * 需要手动给容器中添加该组件
     * 使用redis实现分布式session共享的时候 不需要添加此组件
     * 需要添加{@link SpringSessionBackedSessionRegistry} {@link FindByIndexNameSessionRepository} 这两个组件
     *
     * @return
     */
    // @Bean
    // public HttpSessionEventPublisher httpSessionEventPublisher() {
    //     return new HttpSessionEventPublisher();
    // }
}
